package servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Miss Chen
 * @version 1.0
 * @date 2024年09月09日10:04
 */

@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();
        DiskFileItemFactory  factory=new DiskFileItemFactory();
        ServletFileUpload upload=new ServletFileUpload(factory);
        try {
            //解析请求
            List<FileItem> fileItems=upload.parseRequest(request);
            System.out.println(fileItems.size());//集合中只有2条信息
            Map<String,FileItem> items=new HashMap<>();
            System.out.println(items);
            System.out.println("===================");
            for(FileItem item:fileItems){
                System.out.println(item.getFieldName()+"******");//2次 username    file
                items.put(item.getFieldName(),item);
            }
            System.out.println(items);
            //获取服务器的根目录
            String path=getServletContext().getRealPath("/upload"+new SimpleDateFormat("yyyyMMdd").format(new Date()));
            File f=new File(path);
            f.mkdirs();
            System.out.println("用户名:"+items.get("username").getString("utf-8"));
            FileItem file=items.get("file");
            System.out.println(file.getName());//获取上传文件的名称
            file.write(new File(path,file.getName()));
            out.println("<span>恭喜您，上传成功</span>");
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
